package com.coolw.jdbc.util;

import org.apache.commons.dbcp.BasicDataSource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据库连接池工具类
 *
 * @author coolw
 * @date 2023/12/9 15:35
 */
public final class DbPoolUtil {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /**
     * 数据源
     */
    private static BasicDataSource dataSource;

    static {
        Properties prop = new Properties();
        try (InputStream is = DbPoolUtil.class.getClassLoader().getResourceAsStream("jdbc.properties")) {
            // 加载配置文件
            prop.load(is);

            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");

            // 创建数据源
            dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driver);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            // 设置初始连接数量
            dataSource.setInitialSize(3);
            // 设置最大连接数量
            dataSource.setMaxActive(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        // 获取连接
        return dataSource.getConnection();
    }

    /**
     * 关闭资源:关闭顺序与使用顺序相反，依次关闭顺序为ResultSet,Statement,Connection
     */
    public static void close(Connection conn, Statement stat, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                // 打开自动提交
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
